package com.listener;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.DruidWebUtils;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

@WebListener
public class RequestListener implements ServletRequestListener {
    private Connection conn;
    private static DataSource dataSource;

    static {
        try {
            InputStream resourceAsStream = DruidWebUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties=new Properties();
            properties.load(resourceAsStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest req = (HttpServletRequest) sre.getServletRequest();
        if (!req.getServletPath().endsWith("html") && !req.getServletPath().endsWith("htm")) {
            try {
                this.conn = dataSource.getConnection();
                sre.getServletRequest().setAttribute("conn",this.conn);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
